package com.ruoyi.web.controller.pv;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.doudou.core.container.ListUtil;
import cn.hutool.core.date.*;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.doudou.core.lang.ObjUtil;
import com.ruoyi.cert.domain.Cert;
import com.ruoyi.cert.service.ICertService;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.aliyun.MySms;
import com.ruoyi.pv.domain.PvTrainingClass;
import com.ruoyi.pv.domain.PvUserInfo;
import com.ruoyi.pv.domain.vo.PvStudentRecordExcelVo;
import com.ruoyi.pv.service.IPvClassScoreService;
import com.ruoyi.pv.service.IPvTrainingClassService;
import com.ruoyi.pv.service.IPvUserInfoService;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.pv.domain.PvStudentRecord;
import com.ruoyi.pv.service.IPvStudentRecordService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 学员报名记录Controller
 *
 * @author zzx
 * @date 2023-04-20
 */
@RestController
@RequestMapping("/pv/stu_record")
public class PvStudentRecordController extends BaseController {

    @Autowired private IPvStudentRecordService pvStudentRecordService;
    @Autowired private IPvTrainingClassService pvTrainingClassService;
//    @Autowired private MySms smsUtil;
    @Autowired private IPvUserInfoService userInfoService;
    @Autowired private IPvClassScoreService classScoreService;
    @Autowired private ICertService certService;

    /**
     * 获取当前机构不在该培训班下的学生
     */
    @GetMapping("/get-not-in-class-student-list/{classId}")
    @ApiOperation("获取当前机构不在该培训班下的学生")
    public AjaxResult getNotInClassStudentList(@PathVariable("classId")Long classId){
        List<JSONObject> map = pvStudentRecordService.getNotInClassStudentList(classId,getDeptId());
        return AjaxResult.success(map);
    }

    /**
     * 批量添加学员
     */
    @PostMapping("/add-more-student/{classId}")
    @ApiOperation("批量添加学员")
    public AjaxResult addMoreStudent(@PathVariable("classId")Long classId,@RequestBody JSONArray ids){
        //生成默认评分表
        List<Integer> childrenScore = pvStudentRecordService.createScore(false);
        List<Integer> puerperaScore = pvStudentRecordService.createScore(true);
        List<PvStudentRecord> beanList = ids.stream().map(id ->
                PvStudentRecord.builder().stuId(Long.parseLong(id.toString())).training(classId).
                childrenScore(childrenScore).puerperaScore(puerperaScore).build()).collect(Collectors.toList());
        int i = pvStudentRecordService.insertPvStudentRecordAll(beanList);
        return toAjax(i);
    }


    /**
     * 根据培训班编号查询该培训班下的学生
     */
    @GetMapping("/student-list/{classId}")
    @ApiOperation("查询培训下的学生列表")
    public TableDataInfo studentList(@PathVariable("classId")Long classId, SysUser user) {
        startPage();
        List<PvStudentRecord> list = pvStudentRecordService.selectPvTrainingClassStudentList(classId,user);
        return getDataTable(list).setData(pvStudentRecordService.isFuture()).setInfo(classScoreService.selectPvClassScoreById(classId));
    }

    /**
     * 根据培训班编号和学生编号查询评分表
     */
    @GetMapping("/getRecord-by-clazz-user/{classId}/{userId}")
    public AjaxResult getRecord(@PathVariable("classId")Long classId,@PathVariable("userId")Long userId){
        return success(pvStudentRecordService.selectPvStudentRecordByClassIdAndUserId(classId,userId));
    }

    /**
     * 新增学员报名记录
     * <p>
     *   学员初复训判断：添加个初复训字段标识
     *   初次导入的 统一改为复训
     *   后期人员判断标准：有去年的报名记录+有去年的颁证时间 都有为复训 缺一为初训
     * <p/>
     * 2024-10-17需求：
     * 1.上岗证有效的人，无法报名初训班
     * 2.上岗证有效的人（除了当年通过初训的学员），才能报复训
     */
    @Log(title = "学员报名", businessType = BusinessType.INSERT)
    @PostMapping("/apply")
    @ApiOperation("学员报名")
    public AjaxResult apply() {
        //查询今年创建的最后一个培训班
        PvTrainingClass clazz = pvTrainingClassService.selectPvTrainingYearLast(getDeptId());
        //查询用户
        SysUser sysUser = getUser();
        boolean isNotfirst = false;//是否不是第一次报名
        //查询今年是否已经预约
        int thisYear = DateUtil.thisYear();//今年
        List<PvStudentRecord> pvStudentRecords = pvStudentRecordService.selectPvStudentRecordList(PvStudentRecord.builder().stuId(sysUser.getUserId()).build());
        if (ObjUtil.isNotEmpty(pvStudentRecords)) {
            for (PvStudentRecord record : pvStudentRecords) {
                if (clazz.getId().equals(record.getTraining())) return AjaxResult.error("您已报名成功 "+ clazz.getName() +" ，请勿重复报名");
            }
            for (PvStudentRecord record : pvStudentRecords) {
                int year = DateTime.of(record.getCreateTime()).year();
                //往年有报名记录
                if (year < thisYear) isNotfirst = true;
                //今年有报名记录
                if (thisYear == year) return AjaxResult.error("您今年已有报名记录，请勿重复报名");
            }
        }
        if (isNotfirst){//去年有报名记录
            if (StrUtil.isBlank(sysUser.getPostsNumber())) return AjaxResult.error("报名失败，未查询到您的上岗证");
            //查询用户的证书
            Cert cert = certService.selectCertByUserId(sysUser.getUserId());
            if (ObjUtil.isNull(cert)) return AjaxResult.error("报名失败，未查询到您的证书");
            if (DateUtil.date().isAfter(cert.getExp())) return AjaxResult.error(StrUtil.format("报名失败，您的证书已在{}失效",cert.getExp()));
        }
        //修改用户状态
        userInfoService.updatePvUserInfo(PvUserInfo.builder().id(sysUser.getUserId()).reservedOne(isNotfirst ? "1" : "0").build());
        PvStudentRecord pvStudentRecord = PvStudentRecord.builder().
                stuId(sysUser.getUserId()).
                puerperaScore(pvStudentRecordService.createScore(false)).//生成默认评分表
                childrenScore(pvStudentRecordService.createScore(true)).
                training(clazz.getId()).build();
        int i = pvStudentRecordService.insertPvStudentRecord(pvStudentRecord);
//        if (i > 0) {
//            //发送短信
//            try {
//                smsUtil.sendClassApply(sysUser.getPhonenumber(), sysUser.getNickName(), clazz.getName(), DateUtil.formatDate(clazz.getStartTime()));
//            } catch (Exception e) {
//                logger.info("发送短信失败", e);
//            }
//        }
        return toAjax(i);
    }

    /**
     * 查询学员报名记录列表
     */
    @GetMapping("/my-list")
    public TableDataInfo myList() {
        return getDataTable(pvStudentRecordService.selectPvStudentRecordList(PvStudentRecord.builder().stuId(getUserId()).build()));
    }

    /**
     * 查询学员报名记录列表
     */
    @PreAuthorize("@ss.hasPermi('pv:stu_record:list')")
    @GetMapping("/list")
    public TableDataInfo list(PvStudentRecord pvStudentRecord) {
        startPage();
        List<PvStudentRecord> list = pvStudentRecordService.selectPvStudentRecordList(pvStudentRecord);
        return getDataTable(list);
    }

    /**
     * 导出学员报名记录列表
     */
    @PreAuthorize("@ss.hasPermi('pv:stu_record:export')")
    @Log(title = "学员报名记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export/{classId}")
    public void export(HttpServletResponse response, @PathVariable("classId")Long classId, SysUser user) {
        List<PvStudentRecord> list = pvStudentRecordService.selectPvTrainingClassStudentList(classId,user);
        System.out.println(list.size());
        List<PvStudentRecordExcelVo> newList = ListUtil.list(true);
        PvStudentRecordExcelVo excelVo;
        for (PvStudentRecord record : list) {
            excelVo = BeanUtil.copyProperties(record,PvStudentRecordExcelVo.class);
            if (ObjUtil.isNotEmpty(record.getStudent())){
                excelVo.setUserInfo(record.getStudent().getUserInfo());
                excelVo.setLoginName(record.getStudent().getUserName());
                excelVo.setUserName(record.getStudent().getNickName());
                excelVo.setPhone(record.getStudent().getPhonenumber());
                excelVo.setPostsNumber(record.getStudent().getPostsNumber());
            }
            if (ObjUtil.isNotEmpty(record.getExStudyReload())){
                excelVo.setExScore(record.getExStudyReload().getScore());
            }
            excelVo.setTableTotal(record.getChildrenTotalPoints() + record.getPuerperaTotalPoints());
            newList.add(excelVo);
        }
        ExcelUtil<PvStudentRecordExcelVo> util = new ExcelUtil<>(PvStudentRecordExcelVo.class);
        util.exportExcel(response, newList, "学员培训班记录数据");
    }

    /**
     * 获取学员报名记录详细信息
     */
    @PreAuthorize("@ss.hasPermi('pv:stu_record:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(pvStudentRecordService.selectPvStudentRecordById(id));
    }

    /**
     * 新增学员报名记录
     */
    @PreAuthorize("@ss.hasPermi('pv:stu_record:add')")
    @Log(title = "学员报名记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody PvStudentRecord pvStudentRecord) {
        return toAjax(pvStudentRecordService.insertPvStudentRecord(pvStudentRecord));
    }

    /**
     * 修改学员报名记录
     */
    @PreAuthorize("@ss.hasPermi('pv:stu_record:edit')")
    @Log(title = "学员报名记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody PvStudentRecord pvStudentRecord) {
        return toAjax(pvStudentRecordService.updatePvStudentRecord(pvStudentRecord));
    }

    /**
     * 批量颁证 ids
     */
    @PreAuthorize("@ss.hasPermi('pv:stu_record:edit')")
    @Log(title = "批量颁证", businessType = BusinessType.UPDATE)
    @PutMapping("/complete-cert-ids/{ids}")
    public AjaxResult completeCertIds(@RequestBody Cert cert,@PathVariable("ids") Long[] ids) {
        cert.setStudentIds(ids);
        cert.setApprovalDate(new Date());
        cert.setApprovalBy(getUser().getNickName());
        cert.setApprovalInfo("发证");
        pvStudentRecordService.submitCert(cert);
        return AjaxResult.success("操作成功，正在后台操作");
    }

    /**
     * 批量颁证 query
     */
    @PreAuthorize("@ss.hasPermi('pv:stu_record:edit')")
    @Log(title = "批量颁证", businessType = BusinessType.UPDATE)
    @PutMapping("/complete-cert-query")
    public AjaxResult completeCertQuery(@RequestBody Cert cert) {
        //根据查询条件获取该报名班下全部学生
        List<PvStudentRecord> pvStudentRecords = pvStudentRecordService.selectPvTrainingClassStudentList(cert.getClassId(), cert.getStudent());
        cert.setStudentIds(pvStudentRecords.stream().map(PvStudentRecord::getStuId).toArray(Long[]::new));
        cert.setApprovalDate(new Date());
        cert.setApprovalBy(getUser().getNickName());
        cert.setApprovalInfo("发证");
        pvStudentRecordService.submitCert(cert);
        return AjaxResult.success("操作成功，正在后台操作");
    }

    /**
     * 批量结业
     */
    @PreAuthorize("@ss.hasPermi('pv:stu_record:edit')")
    @Log(title = "批量结业", businessType = BusinessType.UPDATE)
    @PutMapping("/completeCourses/{classId}/{ids}")
    public AjaxResult completeCourses(@PathVariable("classId")Long classId,@PathVariable("ids") Long[] ids) {
        return toAjax(pvStudentRecordService.completeCourses(classId,ids));
    }

    /**
     * 删除学员报名记录
     */
    @PreAuthorize("@ss.hasPermi('pv:stu_record:remove')")
    @Log(title = "学员报名记录", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(pvStudentRecordService.deletePvStudentRecordByIds(ids));
    }
}
